package test_pkg

import (
	"container/heap"
	"fmt"
)

type Initheap []int

func (h Initheap) Len() int {
	return len(h)
}

func (h Initheap) Less(i, j int) bool {
	//小顶堆
	// return h[i] < h[j]

	//大顶堆
	return h[i] > h[j]
}

func (h Initheap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *Initheap) Push(x any) {
	*h = append(*h, x.(int))
}

func (h *Initheap) Pop() any {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

func Test_heap() {
	//方式 1
	h := &Initheap{2, 1, 5}
	heap.Init(h)
	heap.Push(h, 3)
	fmt.Printf("top: %d\n", (*h)[0])
	for h.Len() > 0 {
		fmt.Printf("%d", heap.Pop(h))
	}
	fmt.Println("")

	//方式 2 直接使用 Push
	fmt.Println("---直接 Push ---")
	n := []int{5, 6, 1, 3, 4, 8, 9}
	h1 := &Initheap{}

	for _, v := range n {
		heap.Push(h1, v)
	}

	for h1.Len() > 0 {
		fmt.Printf("%d", heap.Pop(h1))
	}

}
